<!-- 工具库 -->
<template>
  <MenuPage
      ref="selectCard" 
      :columns="columns"
      :data="dataList"
      :loading="loading" 
      :total="total"
      :page.sync="query.pageIndex"
      :size.sync="query.pageSize"
      showSelectTag
      :selection.sync="selection" 
      @queryFun="getToolList">
        <template slot="search">

<!--          <Divider type="vertical" />-->
          <div style="height: 32px;line-height: 32px;flex-shrink: 0;">
            <Checkbox v-model="creatByMe" @on-change="changePage(1)">由我创建</Checkbox>
          </div>
          <Input
            clearable
            v-model.trim="query.name"
            placeholder="工具名称"
            @on-change="debounceSearch"
            style="width: 180px;margin-left: 15px"
          />
          <Select filterable
            v-model="query.visibility"
            clearable
            @on-change="changePage(1)"
            placeholder="可见范围"
            style="width: 150px;margin-left: 15px"
          >
            <Option value="public">系统</Option>
            <Option value="share">单位</Option>
            <Option value="private">个人</Option>
          </Select>
          <Select filterable v-model="query.accessType" placeholder="接入类型" clearable  @on-change="changePage(1)">
            <Option v-for="item in accessTypeList" :key="item" :value="item">{{
              item
            }}</Option>
          </Select>
          <!-- <Select filterable
            v-model="query.copyStatus"
            clearable
            @on-change="changePage(1)"
            placeholder="同步状态"
            style="width: 150px;margin-left: 15px"
          >
            <Option :value="0">未同步</Option>
            <Option :value="1">同步成功</Option>
            <Option :value="2">同步中</Option>
            <Option :value="3">同步失败</Option>
          </Select> -->
          <!-- <Select filterable
            v-model="query.type"
            clearable
            @on-change="changePage(1)"
            placeholder="工具类型"
            style="width: 150px;margin-left: 15px;"
          >
            <Option v-for="item in typeList" :key="item.dictid" :value="item.dictid">{{
              item.dictname
            }}</Option>
          </Select> -->
          <Poptip title="如果没有选择工具，将会同步所有的【由我创建】工具到工具库系统，确认同步吗?" word-wrap width="300" confirm  transfer :disabled="copyloading" @on-ok="batchSyncTool">
            <Button type="primary" ghost icon="md-refresh"  :loading="copyloading" :disabled="copyloading">同步工具库</Button>
          </Poptip>
          <Button v-if="toolAcountInfo.status === 3" type="primary" ghost class="md-add-jh" @click="resetToolAccount"><i class="el-icon-edit"/>生成工具库账号</Button>
          <Button type="primary" ghost class="md-add-jh" @click="addFlowModal"><i class="el-icon-edit"/>创建</Button>
          <Button type="primary" ghost class="md-add-jh" @click="shareGroup"><i class="el-icon-edit"/>批量分享</Button>
          
          <Button
            type="primary"
            ghost
            style="height: 32px;margin-left: 5px;"
            @click="refreshData()"
          >
            <i class="el-icon-refresh-right" />
          </Button>
    </template>
    <template slot="content">
        <div class="account-wrap" v-show="toolAcountInfo.name && toolAcountInfo.status === 1">
          工具库账号：<b>{{ toolAcountInfo.name }} </b>
          <Divider type="vertical"/>
          密码：<b>{{toolAcountInfo.password}} </b>
          <Button type="primary" size="small" shape="circle" icon="ios-create-outline" @click="openPasswordModal" title="修改密码"></Button>
          <Poptip title="确认重置密码?" confirm  transfer @on-ok="changePassword('reset')">
            <Button type="primary" size="small" shape="circle" icon="ios-refresh-circle-outline" title="重置密码"></Button>
          </Poptip>
        </div>
        <div class="filter-wrap">
          <tag-select
              title="类别"
              :current="query.type1"
              :data="level1Arr"
              @on-change="changeTypeLevel1"
          ></tag-select>
          <Divider style="margin:15px 0px" />
          <tag-select
              v-show="showLevel2Arr.length > 0"
              title="类型"
              ref="directionType"
              :current="query.type2"
              :data="showLevel2Arr"
              @on-change="changeType"
          ></tag-select>
          <Divider v-show="showLevel2Arr.length > 0" style="margin:15px 0px" />
          <tag-select
            v-show="showLevel3Arr.length > 0"
            title="子类"
            ref="directionType3"
            :current="query.type3"
            :data="showLevel3Arr"
            @on-change="changeType2"
          ></tag-select>
          <Divider v-show="showLevel3Arr.length > 0" style="margin:15px 0px" />
        </div>
      <!-- </div> -->
    </template>
    <Modal
      v-model="modal.show"
      :title="modal.title"
      :mask-closable="false"
      width="500"
      @on-ok="formBtn('formValidate')"
      @on-cancel="hideModal"
      :closable="false"
      :loading="modal.loading"
    >
      <Form ref="formValidate" :model="formValidate" :rules="formValidateRule" :label-width="100">
        <FormItem label="工具名称" prop="name">
          <Input v-model.trim="formValidate.name" placeholder="工具名称长度为1-64个字符"></Input>
        </FormItem>
        <FormItem label="可见范围" prop="visibility">
          <RadioGroup v-model="formValidate.visibility">
            <Radio label="share">单位</Radio>
            <Radio label="private">个人</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="工具类型" prop="type">
          <Cascader :data="typeList" v-model="formValidate.type"/>
          <!-- <Select filterable v-model="formValidate.type">
            <Option v-for="item in typeList" :key="item.dictid" :value="item.dictid">{{
              item.dictname
            }}</Option>
          </Select> -->
        </FormItem>
        <FormItem label="工具源文件" prop="file">
          <part-upload
            ref="fileUpload"
            @upload-success="uploadSuccess"
            @del-item="deleteFile"
            @upload-loading="handleFileUploading"
            :isSingle="true"
            bucket='toolkit'
            :fileList="toolFileList"
            :isConfirm="false"
            :allFileType="true"
          ></part-upload>
        </FormItem>
        <FormItem label="说明文档" prop="guide">
          <part-upload
            ref="guideUpload"
            @upload-success="changeGuide"
            @del-item="deleteGuide"
            @upload-loading="handleFileUploading"
            fileType="docs"
            :isSingle="true"
            :isConfirm="false"
            :fileList="guideList"
            :formatArr="['doc', 'docx', 'pdf']"
          ></part-upload>
        </FormItem>
        <FormItem label="附件" prop="poc">
          <item-upload
            ref="pocUpload"
            @upload-success="changePoc"
            @del-item="deletePoc"
            @upload-loading="handleFileUploading"
            fileType="docs"
            :isSingle="true"
            :isConfirm="false"
            :fileList="pocList"
            :formatArr="['txt']"
          ></item-upload>
        </FormItem>
        <FormItem label="接入类型" prop="accessType">
          <Select filterable v-model="formValidate.accessType">
            <Option v-for="item in accessTypeList" :key="item" :value="item">{{
              item
            }}</Option>
          </Select>
        </FormItem>
        <FormItem label="设备名称" prop="deviceName" v-if="showToolkitDeviceName">
          <Input
            v-model.trim="formValidate.deviceName"
            :maxlength="64"
            placeholder="设备名称"
          ></Input>
        </FormItem>
        <FormItem label="描述" prop="description">
          <Input
            v-model.trim="formValidate.description"
            type="textarea"
            :maxlength="200"
            :autosize="{ minRows: 2, maxRows: 5 }"
            placeholder="描述"
          ></Input>
        </FormItem>
      </Form>
    </Modal>
    <!-- 修改密码 -->
  <Modal v-model="passwordModal" title="修改密码" width="400" :closable="false" :mask-closable="false" @on-cancel="passwordForm.password = ''" class-name="vertical-center-modal">
    <div>
      <Form ref="passwordForm" :model="passwordForm" :rules="passwordFormRule">
        <FormItem prop="password">
          <Input
            type="text"
            placeholder="请输入新密码"
            v-model.trim="passwordForm.password"
            clearable
          ></Input>
        </FormItem>
      </Form>
    </div>
    <div slot="footer">
      <Button
        type="default"
        @click="
          passwordModal = false;
          passwordForm.password = '';
        "
        >取消</Button
      >
      <Button
        :disabled="
          !/^(?!.*\s)(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[\W_]).{8,20}$/.test(
            passwordForm.password
          )
        "
        type="primary"
        @click="changePassword()"
        >确定</Button
      >
    </div>
  </Modal>
  <!-- 分享 -->
  <Modal
    :closable="true"
    :mask-closable="false"
    width="1000"
    v-model="addUserModal"
    @on-visible-change="changeModalStatus"
    :loading="submitAddMemLoading"
    title="创建分享">
    <div style="display: flex;justify-content: flex-end;margin-bottom: 15px">
        <Input
            v-model.trim="userModal.groupName"
            placeholder="实验组名称"
            style="width: 150px;margin-right: 15px"
            clearable
            @on-change="modalDebounceFn()"
        />
        <Input
            v-model.trim="userModal.userName"
            placeholder="成员名"
            style="width: 150px;margin-right: 15px"
            clearable
            @on-change="modalDebounceFn()"
        />
        <Button title="重置" @click="refreshAddGroupList"
            ><i class="el-icon-refresh-right"
        /></Button>
    </div>
    <TableList
        :showPage="false"
        :columns="userModal.columns"
        :data="userModal.data"
        :page="userModal.pageIndex"
        :total="userModal.total"
        :size="userModal.pageSize"
        showSelectTag
        :selection.sync="chooseList" 
    ></TableList>
    <template slot="footer">
        <div class="flex-between">
          <div>
            <Button
                style="margin-right: 15px"
                type="primary"
                @click="addShares"
                :loading="submitAddMemLoading"
                >添加</Button
            >
            <Button @click="addUserModal = false">取消</Button>
        </div>
        <MyPage :current.sync="userModal.pageIndex"
          :total="userModal.total"
          show-total
          :page-size.sync="userModal.pageSize" @queryFun="getModalList"></MyPage>
        </div>
    </template>
</Modal>
  <!-- 已分享列表 -->
  <Modal
    :closable="true"
    :mask-closable="false"
    width="1000"
    v-model="shareListShow"
    title="已分享列表"
    :footer-hide="true">
      <TableList
          :columns="shareColumns"
          :data="shareData"
          :total="shareTotal"
          :page.sync="queryShare.pageIndex"
          :size.sync="queryShare.pageSize"
          @queryFun="getShareList"
      ></TableList>
  </Modal>
  <Modal
    :closable="true"
    :mask-closable="false"
    width="1000"
    v-model="testProjectModal.show"
    :title="testProjectModal.title"
    :footer-hide="true">
      <TableList
          :columns="testProjectCol"
          :data="testProjectData"
          :total="testProjectTotal"
          :page.sync="queryProject.pageIndex"
          :size.sync="queryProject.pageSize"
          @queryFun="getTestProjectList"
      ></TableList>
  </Modal>
  </MenuPage>
</template>

<script>
import encryption from '@/libs/encryption.js';
import { getToolManageList,deleteToolManage,addOrUpdateToolManage,syncTool,batchSyncTool,getToolAccount,resetPassword,resetToolAccount,toolShare,toolShares,cancelShare,shareList,testProjectList } from '@/api/tool-manage';
import ItemUpload from '@/components/item-upload';
import PartUpload from "@/components/item-upload/partUpload.vue";
import TagSelect from '@/components/tagSelect/tagSelect';
import { allDirection } from '@/api/dict';
import pageTitle from '@/mixin/pageTitle';
import { getGroupHasUsers } from '@/api/company';
import { validateName1 } from '@/libs/reg';
import { debounce, showTimeNotSecond} from '@/libs/utils';
import { visibleMixin } from '@/mixin/study'
import toolTypeMixin from '@/mixin/dictMixin'
export default {
  mixins: [pageTitle,visibleMixin,toolTypeMixin],
  components: {
    PartUpload,
    ItemUpload,
    TagSelect
  },
  data() {
    const validateUpload = (rule, value, callback) => {
      if (this.formValidate.file === null) {
        callback(new Error('请选择文件'));
      } else {
        callback();
      }
    };
    let regPasswd = /^(?!.*\s)(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[\W_]).{8,16}$/; // 密码必须包含大小写字母、数字和特殊字符，长度为8-16
    const validatePass = (rule, value, callback) => {
      if (regPasswd.test(value)) {
        callback();
      } else {
        callback(new Error('密码必须包含大写字母，小写字母，数字和特殊字符，长度为8-16位'));
      }
    };
    return {
        submitAddMemLoading: false,
        shareListShow: false,
        shareData: [],
        shareTotal:0,
        queryShare:{
          pageIndex:1,
          pageSize:10
        },
        chooseList: [], // 已选用户
        userModal: {
          pageIndex: 1,
          total: 0,
          pageSize: 10,
          groupName: '',
          userName: '',
          data: [],
          columns: [
              {
                  type: 'selection',
                  width: 60,
              },
              {
                  title: '实验组名',
                  key: 'name',
                  tooltip:true
              },
              {
                  title: '创建人',
                  key: 'creatorName',
                  tooltip:true
              },
              {
                  title: '创建时间',
                  key: 'created',
                  tooltip:true
              },
              {
                  title: '成员',
                  key: 'userList',
                  tooltip:true,
                  filter:(userList) => {
                    return userList.map(item => {
                      return item.nickname
                    }).join(',')
                  }
              },
          ],
      },
      shareColumns: [
          {
              title: '实验组名',
              key: 'groupName',
          },
          {
              title: '分享人',
              key: 'creatorName',
          },
          {
              title: '分享时间',
              key: 'createTime',
          },
          {
          title: '操作',
          key:'action',
          placement: 'top-right',
          width: 65,
          opList:[
            {
              txt: '删除',
              tooltip: true,
              type: 'delete',
              title: '确定要删除吗？',
              on: {
                click: (data,e) => {
                  cancelShare(data.id).then(res => {
                    // console.log('删除',res)
                    if(res.code == 1) {
                      this.$Message.success('删除成功')
                      this.queryShare.pageIndex = this.shareData.length === 1 && this.queryShare.pageIndex > 1 ? this.queryShare.pageIndex -- : this.queryShare.pageIndex;
                      this.getShareList()
                    }
                  })
                }
              }
            }
          ]
        },
      ],
      addUserModal: false,
      shareWay: '', // 1-批量分享 2-单个分享 
      currentId: '',
      title:'工具',
      creatByMe: false,
      query:{
        pageIndex:1,
        pageSize:10,
        name:'',
        visibility:'',
        type1: "All",
        type2:"All",
        type3:"All"
      },
      selection:[],
      checkAll:false,
      checkAllDisabled:false,
      typeList: [],
      toolFileList: [],
      guideList: [],
      pocList:[],
      // 用户信息
      USER_ID: '',
      isRootDesigner: '',
      // 页面设置
      fullHeight: document.documentElement.clientHeight,
      fullWidth: document.documentElement.clientWidth,
      setTableHei: 'auto',
      // 数据
      dataList: [],
      total: 0,
      loading:false,
      // 查看
      modal:{
        show:false,
        title: '创建工具',
        loading:true
      },
      upLoadUrl: ``,
      fileUploading: false,
      accessTypeList:['rdp','console'],
      formValidate: {
          bucket: "toolkit",
          description: "",
          id: "",
          name: "",
          file:null,
          guide:null,
          poc:null,
          type:[],
          visibility: "share",
          accessType:'',
          deviceName:''
      },
      formValidateRule: {
        name: [
          { required: true, message: '工具名称不能为空', trigger: 'change,blur' },
          { max: 64, message: '工具名称长度为1-64个字符', trigger: 'change,blur' },
          { validator: validateName1, trigger: 'change,blur' }
        ],
        visibility: [{ required: true, message: '可见范围不能为空', trigger: 'change,blur' }],
        type: [{ required: true, type:'array', min:1, message: '工具类型不能为空', trigger: 'change,blur' }],
        file: [{ required: true, validator: validateUpload, trigger: 'change,blur' }]
      },
      columns: [
        {
            type: 'selection',
            width: 60,
            align: 'left'
        },
        {
          title: '工具名称',
          key: 'name',
          minWidth:100,
          toolitp: true,
          placement:'top-left'
        }, 
        {
          title: '类型',
          key: 'type',
          minWidth:100,
          tooltip:true,
          filter:this.getTypeName
        },
        {
          title: '可见范围',
          key: 'visibility',
          width:100,
          render:(h,params) => {
            return h('span',{
              style:{
                color:this.filterVisible(params.row.visibility,'color')
              }
            },this.filterVisible(params.row.visibility,'text'))
          }
        },
        {
          title: '工具文件名',
          key: 'fileName',
          minWidth:100,
          tooltip:true,
          filter:(fielName,data) =>{
            return data.fileName || data.originName
          } 
        },  
        {
          title:'工具大小',
          key: 'size',
          minWidth:100,
          tooltip:true,
          filter:(size) => {
            function getSize(val) {
              let type = '';
              if (val > 1024 * 1024) {
                val = val / (1024 * 1024);
                type = ' MB';
              } else {
                val = val / 1024;
                type = ' KB';
              }
              val = val.toFixed(2);
              return val + '' + type;
            }
            return getSize(size)
          }
        },
        {
          type:'link',
          title:'说明文档',
          key:'guideName',
          minWidth:100,
          tooltip:true,
          setPath:(item) => {
            return `/api/minio/download?path=${item.guidePath}`
          }
        },
        {
          type:'link',
          title:'附件',
          key:'pocName',
          minWidth:100,
          tooltip:true,
          setPath:(item) => {
            return `/api/minio/download?path=${item.pocPath}`
          }
        },
        {
          title:'同步状态',
          key:'cloneStatus',
          minWidth:140,
          placement:"top-right",
          render:(h,params) => {
            return h('div',{
              style:{
                display:'flex'
              }
            },[
              h('Tag',{
                props:{
                  color:this.filterCopyStatus(params.row.copyStatus).color
                },
                style:{
                  flex:'none'
                }
              },this.filterCopyStatus(params.row.copyStatus).text),
              h('Icon',{
                class:'md-sync',
                props:{
                  type:'md-sync',
                  size:26,
                },
                style:{
                  display:this.setReBtnStatus(params.row) || params.row.copyStatus !== 3 ? 'none' :''
                },
                on:{
                  click:() => {
                    this.syncTool(params.row)
                  }
                }
              })
            ])
          }
        },
        {
          title: '接入类型',
          key: 'accessType',
          minWidth:100,
          tooltip: true,
        },
        {
          title:'设备名称',
          key:'deviceName',
          tooltip:true,
          show:() => {
            return this.showToolkitDeviceName
          }
        },
        {
          title: '描述',
          key: 'description',
          minWidth:100,
          tooltip: true,
        },
        {
          title: '创建者',
          key: 'creatorName',
          minWidth:100,
          tooltip: true,
        },
        {
          title: '创建时间',
          key: 'createTime',
          width:150,
          tooltip: true,
        }, 
        {
          title: '操作',
          key:'action',
          fold:true,// 按钮折叠
          foldWidth:'242px',// 展开按钮的背板大小
          placement: 'top-right',
          width: 100,
        //  fixed:'right',
          opList:[
            {
              txt:'分享',
              disabled: (data) => data.visibility != 'private',
              on: {
                  click: (data) => {
                    this.shareWay = '2' // 单个
                    this.addUserModal = true
                    this.currentId = data.id
                    this.refreshAddGroupList()
                  }
                }
            },
            {
              txt:'已分享列表',
              disabled: (data) => data.visibility != 'private',
              on: {
                click: async (data) => {
                  let id = data.id
                  this.currentId = id
                  this.queryShare = {pageIndex:1,pageSize:10}
                  await this.getShareList();
                  if(this.shareTotal > 0){
                    this.shareListShow = true
                  }else{
                    this.$Message.warning('暂无已分享列表')
                  }
                }
              }
            },
            {
              txt:'测试项目列表',
              on: {
                click: async (data) => {
                  let id = data.id
                  this.currentId = id
                  this.queryProject = {pageIndex:1,pageSize:10}
                  await this.getTestProjectList();
                  if(this.testProjectTotal > 0){
                    this.testProjectModal.show = true
                  }else{
                    this.$Message.warning('暂无测试项目列表')
                  }
                }
              }
            },
            {
              txt:'下载',
              type:'download',
              on: {
                click: (data,e) => {
                  this.downloadFile(data);
                }
              },
            },
            {
              txt:'修改',
              type:'modify',
              disabled:this.setReBtnStatus,
              on: {
                click: (data,e) => {
                  this.updateTool(data);
                }
              }
            },
            {
                txt: '删除',
                tooltip: true,
                type: 'delete',
                title: '确定要删除吗？',
                disabled: this.setReBtnStatus,
                on: {
                  click: (data,e) => {
                    this.deleteTool(data)
                  }
                }
            }
          ]
        },
      ],
      toolAcountInfo:{
        userName:'',
        password:'',
        name:''
      },
      passwordModal:false,
      passwordForm:{
        password:''
      },
      passwordFormRule: {
        password: [
          { required: true, validator: validatePass, trigger: 'change' },
          { type: 'string', min: 8, max: 20, message: '密码不能为空', trigger: 'change' }
        ]
      },
      toolUrl:"",
      level1Arr:[], //类别
      level2Arr:[], //类型
      level3Arr:[], //子类
      showLevel2Arr:[],
      showLevel3Arr:[],
      copyloading:false,
      queryProject:{
        pageIndex:1,
        pageSize:10
      },
      testProjectModal:{
        show:false,
        title:'测试项目列表'
      },
      testProjectData: [],
      testProjectTotal:0,
      testProjectCol:[
        {
          title:'测试项目名称',
          key:'name',
          tooltip:true
        },
        {
          title:'测试类型',
          key:'type',
          tooltip:true,
          filter:(type,data) => this.typeFilter(type,data)
        },
        {
          title:'测试单位',
          key:'companyName',
          tooltip:true
        },
        {
          title:'测试日期',
          key:'startTime',
          filter:(startTime,data) => {
            return `${showTimeNotSecond(startTime)} - ${showTimeNotSecond(data.endTime)}`
          },
          tooltip:true,
          minWidth:300
        },
        {
          title:'备注',
          key:'descroption',
          tooltip:true
        }
      ],
      showToolkitDeviceName:false
    };
  },
  computed:{
    emergencyDefenseDrill () { // 应急
       return this.$store.getters.getMenuName('emergencyDefenseDrill');
    },
    awdDrill () { // 对抗
       return this.$store.getters.getMenuName('awdDrill');
    },
    stDrill () { // 渗透
      return this.$store.getters.getMenuName('stDrill');
    },
    multipleDrill () { // 综合
      return this.$store.getters.getMenuName('multipleDrill');
    },
    hwDrill () { // 实网
      return this.$store.getters.getMenuName('hwDrill');
    },
    swDrill () { // 旧护网
      return this.$store.getters.getMenuName('swDrill');
    },
    awdContest () { // 攻防
      return this.$store.getters.getMenuName('awdContest');
    },
    awdPlusContest () { // 攻防Plus
      return this.$store.getters.getMenuName('awdPlusContest');
    },
    ctfContest () { // 夺旗
      return this.$store.getters.getMenuName('ctfContest');
    },
    opContest () { // 运维
      return this.$store.getters.getMenuName('opContest');
    },
    kcContest () { // 知识
      return this.$store.getters.getMenuName('kcContest');
    },
    zcDrill () { // 众测
      return this.$store.getters.getMenuName('zcDrill');
    },
    fzDrill () { // 仿真
      return this.$store.getters.getMenuName('fzDrill');
    },
    dailyDrill () { // 日常
      return this.$store.getters.getMenuName('dailyDrill');
    },
    bigDrill(){ // 大型
      return this.$store.getters.getMenuName('bigDrill');
    }
  },
  created() {
    // 获取用户id
    let November = sessionStorage.getItem('November');
    November = JSON.parse(encryption.SelfUseDecrypt(November));
    this.USER_ID = November.userId;
    this.userName = November.userName;
    this.isRootDesigner = November.isRootDesigner;
    this.upLoadUrl = `api/minio/upload/permanent?visibility=company&type=pcap&bucket=pcap`;
    this._formValidate = {...this.formValidate};
  },
  mounted() {
    this.getDictByName('tools').then(res => {
      let {treeData,data} = res;
      let level2Arr = this.getLevelData(data,2);
      let level3Arr = this.getLevelData(data,3);
      this.level1Arr = this.getLevelData(data,1);
      this.level2Arr = level2Arr;
      this.level3Arr = level3Arr;
      this.showLevel2Arr = level2Arr;
      this.showLevel3Arr = level3Arr;
      this.typeList = treeData;
      this.allType = data;
    });
    this.getToolList();
    this._query = {...this.query};
    this.$store.dispatch('common/getSysConfigShow','showOpLastScoreTime').then(data => {
        this.showToolkitDeviceName = data
    })
    // this.setStyle();
    // window.addEventListener('resize', this.setStyle);
    // this.getModalList()
  },
  beforeDestroy() {
    clearTimeout(this.timeout)
    clearTimeout(this.timeoutList);
  },
  methods: {
    getShareList(){
      return new Promise((resolve,reject) => {
        shareList(this.currentId,this.queryShare).then(res => {
          if(res.code == 1) {
            this.shareData = res.data.items;
            this.shareTotal = res.data.total;
            resolve()
          }else{
            this.shareData = [];
            this.shareTotal = 0;
            this.$Message.error(res.message);
            reject()
          }
        }).catch(error => {
          this.$Message.error('获取已分享列表失败');
          reject()
        })
      })
    },
    changeSharePage(page){
      this.queryShare.pageIndex = page;
      this.getShareList();
    },
    getTestProjectList(){
      return new Promise((resolve,reject) => {
        testProjectList(this.currentId,this.queryProject).then(res => {
          if(res.code == 1) {
            this.testProjectData = res.data.items;
            this.testProjectTotal = res.data.total;
            resolve()
          }else{
            this.testProjectData = [];
            this.testProjectTotal = 0;
            this.$Message.error(res.message);
            reject()
          }
        }).catch(error => {
          this.$Message.error('获取已分享列表失败');
          reject()
        })
      })
    },
    // 批量分享
    addShares() {
        let chooseIds = this.chooseList.map(item => {
            return item.id
        })
        if(!chooseIds.length) {
            this.$Message.warning('请选择用户')
            return false
        }
        
        let toolIds = this.selection.map(item => item.id)
        let params = {
            groupIds: chooseIds,
            toolsIds: toolIds
        }
        if(this.shareWay == '2') {
          params.toolsIds = [this.currentId]
        }
        this.submitAddMemLoading = true
        toolShares(params).then(res => {
            // console.log('批量分享', res)
            if(res.code == 1) {
                this.$Message.success('分享成功')
                this.chooseList = [];
                this.selection = [];
                this.addUserModal = false
            }else {
                this.$Message.error(res.message)
            }
        }).finally(() => {
            this.submitAddMemLoading = false
        })
        // console.log('chooseIds',chooseIds)
    },
    // 重置搜索条件
    refreshAddGroupList() {
      this.userModal.pageIndex = 1
      this.userModal.groupName = ''
      this.userModal.userName = ''
      this.chooseList = [];
      this.getModalList();
    },
    modalDebounceFn: debounce(function() {
      this.modalPageChange(1)
    }),
    modalPageChange(val) {
        this.userModal.pageIndex = val
        this.getModalList()
    },
    // 获取可选用户列表
    getModalList() {
        let params = {
            pageIndex: this.userModal.pageIndex,
            pageSize: this.userModal.pageSize,
            order: 'desc',
            sortBy: 'created',
            name: this.userModal.groupName,
            nickname: this.userModal.userName,
            local: true,
        }
        getGroupHasUsers(params).then(({data = {}}) => {
            if(data.code == 1) {
                // console.log('data',data)
                // this.userModal.data = data.data.items
                this.userModal.total = data.data.total;
                this.userModal.data = data.data.items || []
            }
        })
    },
    // 关闭模态框，重置搜索条件
    changeModalStatus(val) {
      if (!val) {
        this.refreshAddGroupList();
      }
    },
    shareGroup() {
      let flag = this.selection.every(item => {
        return item.visibility == 'private'
      })
      if(!flag) {
        this.$Message.warning('仅可分享个人工具库')
        return false
      }
      let ids = this.selection.map(item => item.id)
      if(ids.length == 0) {
        this.$Message.warning('请先选择工具')
        return false
      }
      this.shareWay = '1' // 批量
      this.addUserModal = true
    },
    // 设置高度
    setStyle() {
      const contentHeight = this.$refs.cardList.clientHeight;
      const pageHeight = 34 + 10; //this.$refs.page.$el.clientHeight; 分页
      // console.log(contentHeight, pageHeight);
      const height = contentHeight - pageHeight;
      const itemHeight = 96;
      let pageSize = Math.max(Math.floor(height / itemHeight), 1);
      let usePage = this.query.pageIndex,
          maxPage;
      if (this.total > 0) {
          maxPage = Math.ceil(this.total / pageSize);
          usePage = Math.min(this.query.pageIndex, maxPage);
      }
      if (
          pageSize === this.query.pageSize &&
          this.query.pageIndex === usePage &&
          this.hasInit
      ) {
          return;
      }
      this.query.pageIndex = usePage;
      this.query.pageSize = pageSize;
      this._query = {...this.query};
      this.hasInit = true;
      this.getToolList();
    },
    // 获取工具库列表
    getToolList() {
      return new Promise((resolve,reject) => {
        if(this.loading){
          //正在请求，有新的请求
          this.hasNoExecuteRequest = true;
          return
        }
        this.loading = true;
        let query = {
          ...this.query,
          creator: this.creatByMe ? this.USER_ID : undefined
        }
        delete query.type1;
        delete query.type2;
        delete query.type3;
        if(this.query.type1 !== 'All'){
          query.type = this.query.type1
        }
        if(this.query.type2 !== 'All'){
          query.type = this.query.type2
        }
        if(this.query.type3 !== 'All'){
          query.type = this.query.type3
        }
      getToolManageList(this.userName,query)
        .then(({code,data,message}) => {
          if (code == 1) {
            let pageList = data.items;
            this.total = parseInt(data.total);
            this.dataList = pageList.map((item) => {
              // item.typeName = this.getTypeName(item.type);
              item.fileName = item.originName || item.fileName;
              return item;
            });
            if(this.dataList.some(item => item.copyStatus === 2)){ //同步中
              this.timeoutList = setTimeout(() => {
                this.getToolList()
              },5000)
            }else{
              clearTimeout(this.timeoutList);
            }
            if(this.hasNoExecuteRequest){
              this.getToolList()
              this.hasNoExecuteRequest = false
            }
          } else {
            this.dataList = [];
            this.total = 0;
            this.$Message.warning(res.data.message);
            if(this.hasNoExecuteRequest){
              this.getToolList()
              this.hasNoExecuteRequest = false
            }
          }
          this.loading = false;
          if(!(this.toolAcountInfo.name && this.toolAcountInfo.status !== 3)){
            this.getToolAccount();
          }
          resolve()
        })
        .catch((error) => {
          this.loading = false;
          if(this.hasNoExecuteRequest){
            this.getToolList()
            this.hasNoExecuteRequest = false
          }
          console.log(error);
        });
      })
    },
    debounceSearch:debounce(function(){
      this.changePage(1)
    },500),
    changePage(val) {
      this.query.pageIndex = val;
      this.getToolList();
    },
    syncTool(tool){
      let {id,typeName} = tool;
      syncTool(id,typeName).then(({code,data,message}) => {
        if(code === 1){
          this.$Message.info(message)
          this.getToolList()
        }else{
          this.$Message.error(message);
        }
      }).catch(error => {
        console.log(error);
      })
    },
    batchSyncTool(){
      this.copyloading = true;
      let ids = this.selection.map(item => item.id)
      batchSyncTool(ids).then(({code,data,message}) => {
        if(code === 1){
          this.$Message.info(message)
          this.getToolList()
          this.selection = []
        }else{
          this.$Message.error(message);
        }
        this.copyloading = false;
      }).catch(error => {
        console.log(error);
        this.copyloading = false;
      })
    },
    changeType(val) {
      this.query.type3 = 'All';
      this.showLevel3Arr = this.getDictChildren(val,this.allType,this.showLevel2Arr);
      this.query.type2 = val;
      this.debounceSearch();
      this.$refs.directionType3 && this.$refs.directionType3.updateHeight();
    },
    changeTypeLevel1(val) {
      this.query.type2 = 'All';
      this.showLevel2Arr = this.getDictChildren(val,this.allType,this.level1Arr);
      this.changeType('All');
      this.query.type1 = val;
      this.debounceSearch();
      this.$refs.directionType && this.$refs.directionType.updateHeight();
    },
    changeType2(val){
      this.query.type3 = val;
      this.debounceSearch();
    },
    // 刷新
    refreshData() {
      this.creatByMe = false;
      this.query = {...this._query};
      this.showLevel2Arr = this.level2Arr;
      this.showLevel3Arr = this.level3Arr;
      this.selection = [];
      this.getToolList();
    },
    handleFileUploading(status) {
      this.fileUploading = status;
    },
    // 添加了源文件，设置数据
    uploadSuccess(file) {
      this.formValidate.file = file;
      this.toolFileList = [
        {
          id: file.fileId,
          fileName: file.fileName,
          path: file.filePath
        }
      ];
      this.$nextTick(() => {
        this.$refs.formValidate.validateField('file');
      });
    },
    // 删除源文件，将相关数据清除
    deleteFile() {
      this.formValidate.file = null;
      this.toolFileList = [];
      this.$nextTick(() => {
        this.$refs.formValidate.validateField('file');
      });
    },
    // 添加使用手册，设置数据
    changeGuide(file) {
      this.formValidate.guide = file;
      this.guideList = [
        {
          id: file.fileId,
          fileName: file.fileName,
          path: file.filePath
        }
      ];
    },
    deleteGuide() {
      this.formValidate.guide = null;
      this.guideList = [];
      this.formValidate.guideName = ''
      this.formValidate.guidePath = ''
    },
    // 添加脚本，设置数据
    changePoc(file) {
      this.formValidate.poc = file;
      this.pocList = [
        {
          id: file.fileId,
          fileName: file.fileName,
          path: file.filePath
        }
      ];
    },
    deletePoc() {
      this.formValidate.poc = null;
      this.pocList = [];
      this.formValidate.pocName = ''
      this.formValidate.pocPath = ''
    },
    // 添加Flow
    addFlowModal() {
      this.modal.show = true;
      this.formValidate = {...this._formValidate};
      this.modal.title = `创建${this.title}`;
    },
    // 修改Flow
    updateTool(row) {
      this.modal.show = true;
      this.modal.title = `修改${this.title}`;
      this.formValidate = Object.assign({}, row);
      this.formValidate.type = row.type.split(',');
      if (this.formValidate.fileName) {
        let file = {
          fileName: this.formValidate.fileName,
          filePath: this.formValidate.path,
          path:this.formValidate.path,
          fileId:this.formValidate.fileId,
          size:this.formValidate.size
        }
        this.formValidate.file = file;
        this.toolFileList = [file];
      }
      if(this.formValidate.guideName){
        let guide = {
          fileName: this.formValidate.guideName,
          path: this.formValidate.guidePath,
          filePath: this.formValidate.guidePath
        }
        this.formValidate.guide = guide
        this.guideList = [guide];
      }
      if(this.formValidate.pocName){
        let poc = {
          fileName: this.formValidate.pocName,
          path: this.formValidate.pocPath,
          filePath: this.formValidate.pocPath
        }
        this.formValidate.poc = poc
        this.pocList = [poc];
      }
    },
    formBtn(name) {
        if(this.fileUploading){
          this.$Message.info('请等待文件上传完成');
          this.cancelLoading();
          return
        }
        this.$refs[name].validate((valid) => {
          if (valid) {
            let {file,guide,poc,...params} = this.formValidate;
            params.fileName = file.fileName;
            params.fileId = file.fileId;
            params.originName = file.fileName,
            params.size = file.size;
            params.path = file.filePath;
            if(guide){
              params.guideName = guide.fileName;
              params.guidePath = guide.filePath;
            }
            if(poc){
              params.pocName = poc.fileName;
              params.pocPath = poc.filePath;
            }
            params.type = this.formValidate.type.join(',');
            params.typeName = this.getTypeName(params.type);
            addOrUpdateToolManage(params)
              .then(({code,data,message}) => {
                if (code === 1) {
                  this.hideModal();
                  this.refreshData();
                  this.$Message.success(`${this.modal.title}成功`);
                } else {
                  this.$Message.warning(message);
                }
              })
              .catch(() => {
                this.$Message.error(`${this.modal.title}失败`);
              })
              .finally(() => {
                this.cancelLoading();
              });
          } else {
            this.cancelLoading();
            // this.$Message.error('请完善信息！');
          }
        }).catch(error => {
          this.cancelLoading();
        })
    },
    // 删除
    deleteTool(tool) {
      deleteToolManage(tool.id)
        .then(({code,data,message}) => {
          if (code == 1) {
            this.$Message.success('删除成功');
            this.query.pageIndex =
              this.query.pageIndex > 1 && this.dataList.length === 1
                ? this.query.pageIndex - 1
                : this.query.pageIndex;
            this.getToolList();
            this.$refs.selectCard.closeItem(tool);
          } else {
            this.$Message.warning(message);
          }
        })
        .catch((err) => {
          this.$Message.error('删除异常');
        });
    },
    hideModal(){
      this.formValidate = {...this._formValidate};
      this.$refs.formValidate.resetFields();
      this.$refs.fileUpload.cancelUpload();
      this.$refs.guideUpload.cancelUpload();
      this.$refs.pocUpload.cancelUpload();
      this.toolFileList = [];
      this.guideList = [];
      this.pocList = [];
      this.modal.show = false;
    },
    cancelLoading(){
      this.modal.loading = false;
      setTimeout(() => {
        this.modal.loading = true;
      })
    },
    // 按钮点击状态
    setReBtnStatus(params) {
      let userid = params.creator;
      // this.isRootDesigner
      if ((userid === this.USER_ID) && params.visibility != 'public') {
        return false;
      } else {
        return true;
      }
    },
    //获取当前用户工具库账号
    getToolAccount(){
      return new Promise((resolve,reject) => {
        getToolAccount().then(({code,data,message}) => {
          if(code === 1){
            this.toolAcountInfo = data;
            if(this.toolAcountInfo.status === 2){
              this.timeout = setTimeout(() => {
                this.getToolAccount()
              },5000)
            }else{
              clearTimeout(this.timeout)
            }
          }else{

          }
          resolve()
        })
      })
    },
    openPasswordModal(){
      this.passwordForm.password = '';
      this.$refs.passwordForm.resetFields();
      this.passwordModal = true;
    },
    changePassword(type){
      let params = {
        userId:this.USER_ID,
        password:type === 'reset' ?  '' : this.passwordForm.password
      }
      resetPassword(params).then(({code,data,message}) => {
        if(code){
          this.$Message.info(params.password ? '密码修改成功' : '密码重置成功');
          this.passwordModal = false;
          setTimeout(() => {
            this.getToolAccount()
          },3000)
        }else{
          this.$Message.error(message)
        }
      }).catch(error => {
        console.log(error);
      })
    },
    resetToolAccount(){
      resetToolAccount().then(({code,data,message}) => {
        if(code === 1){
          this.$Message.info('账号生成成功');
          this.getToolAccount();
        }else{
          this.$Message.error(message)
        }
      }).catch(error => {
        console.log(error);
      })
    },
    getTypeList() {
      return new Promise((resolve) => {
        allDirection({
          dictTypeID: 'tools'
        })
          .then(({ code, message, attribute = {} }) => {
            if (code !== 1) {
              this.$Message.warning(message);
              return;
            }
            this.typeList =
              (attribute &&
                attribute.attribute &&
                attribute.attribute[0] &&
                attribute.attribute[0].dictEntryList) ||
              [];
          })
          .catch(() => {
            this.$Message.error('获取工具类型列表异常');
          })
          .finally(() => {
            resolve();
          });
      });
    },
    getTypeName(type) {
      return this.handleDictSepShow(type.split(','),this.allType,'，')
    },
    downloadFile(file){
        let {fileId,type} = file;
        let typeName = this.getTypeName(type)
        const msg = this.$Message.loading({
            content: '下载中...',
            duration: 0,
        });
        let href = this.url;
        let a = document.createElement('a');
        document.body.appendChild(a);
        if(this.params){
            let paramsStringArr = [];
            for(let key in this.params){
                if(this.params[key]){
                    paramsStringArr.push(`${key}=${this.params[key]}`)
                }
            }
            let paramsStringTxt = paramsStringArr.join('&')
            href = `${href}?${paramsStringTxt}`
        }
        a.href = `/api/tool-manage/tool/download/${fileId}?accepterName=${this.userName}&typeName=${typeName}`;
        a.download = ''; //命名下载名称
        a.click(); //点击触发下载
        a.remove();
        setTimeout(msg, 500);
    },
    filterCopyStatus(status){
      let text,color;
      if(status === 0) {
        text = '未同步'
        color = 'var(--status-pre)'
      }else if(status === 1){
        text = '同步成功'
        color = 'var(--status-yes)'
      }else if(status === 2){
        text = '同步中'
        color = 'var(--status-ing)'
      }else if(status === 3){
        text = '同步失败'
        color = 'var(--status-no)'
      }
      return {
        text,color
      }
    },
    typeFilter (val,data) {
      //0.对抗演练、1.攻防赛、2夺旗赛、3知识赛、4渗透演练
      let str = '';
      switch (val.toString()) {
        case '0':
          // str = '对抗演练';
          str = this.awdDrill;
          break;
        case '1':
          // str = '攻防赛';
          str = this.awdContest;
          break;
        case '2':
          // str = '夺旗赛';
          str = this.ctfContest;
          break;
        case '3':
          // str = '知识赛';
          str = this.kcContest;
          break;
        case '4':
          // str = '渗透演练';
          str = this.stDrill;
          break;
        case '5':
          let extension = JSON.parse(data.extension);
          let { hwType,hwExtensionType } = extension
          if(hwType === 0){
						str = hwExtensionType === '2' ? this.dailyDrill  : hwExtensionType === 3 ? this.bigDrill : this.swDrill
					}else if(hwType === 1){ //实网(新护网)
            str = this.hwDrill;
          }else if(hwType === 2){ //众测
            str = this.zcDrill;
          }else if(hwType === 3){ //仿真
            str = this.fzDrill;
          }
          break;
        case '6':
          // str = '应急防御演练';
          str = this.emergencyDefenseDrill;
          break;
        case '7':
          // str = '综合演练';
          str = this.multipleDrill;
          break;
        case '8':
          // str = '攻防赛Plus';
          str = this.awdPlusContest;
          break;
        case '9':
          // str = '运维赛';
          str = this.opContest;
          break;
        case '10':
          // str = '应急防御演练';
          str = this.emergencyDefenseDrill;
          break;
        default:
          break;
      }
      return str;
    }
  }
};
</script>
<style scoped>
.account-wrap{
  padding: 10px;
  margin: 0 0 20px;
  background: var(--table-tr-hover-color);
  font-size: 14px;
}
/*查询样式 ---开始*/
.filter-wrap {
  /* padding: 0 0 20px; */
  margin-top:-10px;
  font-size: 14px;
  color: #8f90a6;
}
</style>
<style>
  .md-sync{
    cursor: pointer!important;
  }
  .md-sync:hover{
    color:#1563C2 ;
  }
</style>
